package com.yhos.platform.oopston.service.biz;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yhos.platform.oopston.base.config.OopstonConfig;
import com.yhos.platform.oopston.base.constants.BaseOperatorConstant;
import com.yhos.platform.oopston.base.enums.TrueFalseEnum;
import com.yhos.platform.oopston.base.enums.YesNoEnum;
import com.yhos.platform.oopston.core.exception.BusinessException;
import com.yhos.platform.oopston.core.utils.JacksonUtils;
import com.yhos.platform.oopston.core.utils.ListUtils;
import com.yhos.platform.oopston.core.utils.MessageSourceUtils;
import com.yhos.platform.oopston.mapper.entity.ShunfengOrder;
import com.yhos.platform.oopston.mapper.mapper.ShunfengOrderMapper;
import com.yhos.platform.oopston.mapper.model.RequestBaseModel;
import com.yhos.platform.oopston.mapper.model.shunfeng.ShunfengOrderCreateRequestApiModel;
import com.yhos.platform.oopston.mapper.model.shunfeng.ShunfengOrderCreateResponseApiModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2020/4/19.
 */
@Service
public class ShunfengOrderBiz {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OopstonConfig oopstonConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MessageSourceUtils messageSourceUtils;

    @Autowired
    private ShunfengOrderMapper shunfengOrderMapper;

    @Autowired
    private ShunfengOrderLabelBiz shunfengOrderLabelBiz;

    @Autowired
    private OrderOperateBiz orderOperateBiz;

    private ObjectMapper objectMapper = JacksonUtils.getInstance();

    private static final String OOPSTON_ORDER_CREATE_URL = "http://my.megawms.com/PubApi/AddOrder.aspx";

    private static final String OOPSTON_ORDER_CANCEL_URL = "http://my.megawms.com/PubApi/InvalidOrder.aspx";

    private static final String OOPSTON_GET_TRACK_URL = "http://my.megawms.com/PubApi/GetTrack.aspx";

    private static final String ZHONG_TONG_REQUEST_URL = "http://120.27.146.160:8026/webservice/PublicService.asmx/ServiceInterfaceUTF8";

    private static final String ZHONG_TONG_ORDER_CREATE_METHOD = "createorder";

    private static final String ZHONG_TONG_ORDER_DELETE_METHOD = "removeorder";

    private static final String ZHONG_TONG_TRACK_GET_METHOD = "gettrack";

    private static final String ZHONG_TONG_TAG_GET_METHOD = "getnewlabel";

    private static final String SHUNFENG_ORDER_CREATE_URL = "https://orapi.trackmeeasy.com/lomp-ext/sf-express/contract/receiveOrder ";

    private static final String SHENFENG_API_USERNAME = "yuanhang6";

    private static final String SHENFENG_API_KEY = "c29edee387c9f385fc657881821088ca";


    /**
     * 创建shunfeng订单
     *
     * @param requestApiModel
     * @return
     */
    @Transactional
    public ShunfengOrderCreateResponseApiModel createOrder(ShunfengOrderCreateRequestApiModel requestApiModel) {
        ShunfengOrderCreateResponseApiModel responseApiModel = new ShunfengOrderCreateResponseApiModel();
        List<ShunfengOrder> shunfengOrderList = shunfengOrderMapper.selectList(new EntityWrapper<ShunfengOrder>().eq("Delete_Yn", YesNoEnum.NO.getKey())
               // .eq("Cancel_Status", YesNoEnum.NO.getKey())
                .eq("order_sn",requestApiModel.getOrder_sn()));
                //.in("Channel_Type", Arrays.asList(ChannelTypeEnum.FBA_USOUG.getKey(), ChannelTypeEnum.FBA_USOFG.getKey(), ChannelTypeEnum.FBA_USAFG.getKey(), ChannelTypeEnum.FBA_USAUG.getKey()))
               // .isNotNull("Response_Order_ID"));

        if (ListUtils.isNotEmpty(shunfengOrderList)) {
            responseApiModel.setApi_key(SHENFENG_API_KEY);
            responseApiModel.setApi_username(SHENFENG_API_USERNAME);
//                          (String.valueOf(shunfengOrderList.get(0).getId()));
            responseApiModel.setOrder_sn(shunfengOrderList.get(0).getOrderSn());

            return responseApiModel;
        }


        //相关的单保存在本地 TODO
       // ShunfengOrder order = shunfengOrderLabelBiz.createOrderInfo(requestApiModel);

        //封装接口参数
      //  ShunfengOrderCreateResponseApiModel remoteRequest = buildCreateOrderRemoteRequest(requestApiModel);


        responseApiModel = this.request(SHUNFENG_ORDER_CREATE_URL, requestApiModel, ParameterizedTypeReference.forType(ShunfengOrderCreateResponseApiModel.class));
        if (responseApiModel != null) {
            //如果下游处理失败，将失败原因往外抛
            if (TrueFalseEnum.FALSE.getValue().equalsIgnoreCase(responseApiModel.getSuccess())) {
                //下游返回空处理
                throw new BusinessException(responseApiModel.getMessage(),
                        BaseOperatorConstant.ORDER_CREATE_REQUEST_FAILED);
            } else {
                //shunfengOrderLabelBiz.updateResponse(order.getId(), responseApiModel);
            }
        } else {
            //下游返回空处理
            throw new BusinessException(messageSourceUtils.getMessage(
                    BaseOperatorConstant.ORDER_CREATE_REQUEST_FAILED),
                    BaseOperatorConstant.ORDER_CREATE_REQUEST_FAILED);
        }
        //responseApiModel.setId(String.valueOf(order.getId()));
        responseApiModel.setOrder_sn(requestApiModel.getOrder_sn());
        return responseApiModel;
    }



    /**
     * 包装下游请求公共参数（CusCode、ApiKey、CusApiName）
     *
     * @param requestApiModel
     * @param channelId
     * @param <T>
     * @return
     */
    private <T extends RequestBaseModel> T setPackageChannelInfo(T requestApiModel, String channelId) {
        if (oopstonConfig.getBigPackChannelId().equalsIgnoreCase(channelId)) {
            //如果是大包渠道
            requestApiModel.setCusCode(oopstonConfig.getBigPackCusCode());
            requestApiModel.setApiKey(oopstonConfig.getBigPackApiKey());
            requestApiModel.setCusApiName("跃翰");
        } else if (oopstonConfig.getSmallPackChannelId().equalsIgnoreCase(channelId)) {
            //如果是小包渠道
            requestApiModel.setCusCode(oopstonConfig.getSmallPackCusCode());
            requestApiModel.setApiKey(oopstonConfig.getSmallPackApiKey());
            requestApiModel.setCusApiName("跃翰");
        }
        requestApiModel.setCusApiName(oopstonConfig.getApiName());
        return requestApiModel;
    }

    /**
     * RestTemplate请求方法
     *
     * @param restUrl
     * @param requestModel
     * @param resultClass
     * @param <T>
     * @return
     */
    private <T> T request(String restUrl, Object requestModel, ParameterizedTypeReference<T> resultClass) {
        if (StringUtils.isBlank(restUrl)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<Object> formEntity = new HttpEntity<>(requestModel, headers);
        ResponseEntity<T> resultContent = null;
        String requestHeader = "\n request header : " + getObjectContent(headers);
        String requestContent = "\n , request content : " + getObjectContent(requestModel);
        long startTime = System.currentTimeMillis();
        try {
            resultContent = restTemplate.exchange(restUrl, HttpMethod.POST, formEntity, resultClass);
        } catch (Exception ex) {
            logger.error("restClient request url : " + restUrl + requestHeader + requestContent + "\n , error message : " + ex.getMessage(), ex);
            resultContent = null;
        } finally {
            long endTime = System.currentTimeMillis();
            String responseContent = "\n , response result : " + getObjectContent(resultContent);
            logger.info("restClient request url : " + restUrl + " , use time : " + (endTime - startTime) + requestHeader + requestContent + responseContent);
        }
        return resultContent.getBody();
    }

    /**
     * RestTemplate请求方法
     *
     * @param restUrl
     * @param requestModel
     * @param resultClass
     * @param <T>
     * @return
     */
    private <T> T formRequest(String restUrl, String methodName, Object requestModel, ParameterizedTypeReference<T> resultClass) {
        if (StringUtils.isBlank(restUrl)) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap map = new LinkedMultiValueMap();
        map.add("appToken", oopstonConfig.getZhongTongAppToken());
        map.add("appKey", oopstonConfig.getZhongTongAppKey());
        map.add("serviceMethod", methodName);
        map.add("paramsJson", JSONObject.toJSONString(requestModel));
        HttpEntity formEntity = new HttpEntity(map, headers);
        ResponseEntity<T> resultContent = null;
        String requestHeader = "\n request header : " + getObjectContent(headers);
        String requestContent = "\n , request content : " + JSONObject.toJSONString(requestModel);
        long startTime = System.currentTimeMillis();
        try {
            resultContent = restTemplate.exchange(restUrl, HttpMethod.POST, formEntity, resultClass);
        } catch (Exception ex) {
            logger.error("restClient request url : " + restUrl + requestHeader + requestContent + "\n , error message : " + ex.getMessage(), ex);
            resultContent = null;
        } finally {
            long endTime = System.currentTimeMillis();
            String responseContent = "\n , response result : " + getObjectContent(resultContent);
            logger.info("restClient request url : " + restUrl + " , use time : " + (endTime - startTime) + requestHeader + requestContent + responseContent);
        }
        return resultContent.getBody();
    }

    /**
     * JSON序列化出入参
     *
     * @param object
     * @return
     */
    private String getObjectContent(Object object) {
        if (object == null) {
            return "";
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            logger.error("getObjectContent writeValueAsString error." + e.getMessage(), e);
        }
        return "";
    }

/*    private ShunfengOrderCreateRemoteRequest buildCreateOrderRemoteRequest(ShunfengOrderCreateRequestApiModel remoteRequestModel) {
        ShunfengOrderCreateRemoteRequest remoteRequest = new ShunfengOrderCreateRemoteRequest();
        //remoteRequest.setStyle(requestApiModel.getOrderType());

        remoteRequest = remoteRequestModel;
        return remoteRequest;
    }*/



}
